package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHUtil
import com.google.cloud.translate.v3.*
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.kh.hst
 * @className: apiGoogleTranslate
 * @author: LiJT
 * @description: 华盛证券翻译接口-Google翻译V3V3(高级版)
 * @date: 2023-09-27 11:50
 * @version: 1.0
 */
public class api_GoogleTranslateV3 implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(api_GoogleTranslateV3.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 返回数据及示例
        JSONObject reJson = new JSONObject();
        JSONArray trans_result = new JSONArray();

        //获取参数js_code，登录时获取的 code
        String q = request.getParameter("q");
        String from = request.getParameter("from");
        String to = request.getParameter("to");

        // 语言转码(Chat默认按百度语言字典Google需要转码)
        from = from == "cht" ? "zh-HK" : from == "zh" ? "zh-CN" : from;
        to = to == "cht" ? "zh-HK" : to == "zh" ? "zh-CN" : to;

        // 转义待翻译内容
        String qText = null;
        try {
            qText = URLDecoder.decode(q, "UTF-8");
        } catch (Exception e) {
            log.warn("转义待翻译内容错误：" + e.getMessage());
            qText = q;
        }
        log.debug("接收参数qText：" + q + " from：" + from + " to：" + to + " 转义qText：" + qText);

        try {
            // 调用Google翻译V3
            JSONObject transObject = getTranslate(qText, from, to);

            // 解析Google翻译V3
            if (transObject.getInt("code") == 0) {
                // 翻译结果成功
                JSONArray translations = transObject.getJSONObject("data").getJSONArray("translations");
                for (int i = 0; i < translations.size(); i++) {
                    JSONObject transObj = new JSONObject();
                    transObj.put("src", qText);
                    transObj.put("dst", translations.getJSONObject(i).getString("translatedText"));
                    trans_result.add(transObj);
                }
                reJson.put("trans_result", trans_result);
                reJson.put("trans_message", transObject.getString("message"));
                reJson.put("trans_data", transObject.getJSONObject("data"));
            } else {
                // 翻译结果异常
                JSONObject transObj = new JSONObject();
                transObj.put("src", qText);
                transObj.put("dst", qText);
                trans_result.add(transObj);
                reJson.put("trans_result", trans_result);
                reJson.put("trans_message", transObject.getString("message"));
                reJson.put("trans_data", transObject.getJSONObject("error"));

            }
            log.debug("解析Google翻译V3：" + reJson.toString());

            // 处理返回结果
            reJson.put("from", from);
            reJson.put("to", to);
            log.debug("处理后返回Chat结果：" + reJson.toString());

        } catch (Exception e) {
            log.error("接口处理异常", e);
            reJson.put("from", from);
            reJson.put("to", to);

            JSONObject transObj = new JSONObject();
            transObj.put("src", qText);
            transObj.put("dst", qText);
            trans_result.add(transObj);
            reJson.put("trans_result", trans_result);
            reJson.put("trans_message", e.getMessage());
        }
        log.debug("翻译处理-耗时：" + (System.currentTimeMillis() - startTime) + " 结果：" + reJson.toString());
        return reJson.toString();

    }

    // 调用Google翻译V3
    public static JSONObject getTranslate(String text, String sourceLang, String targetLang) {

        log.debug("调用Google翻译V3入参信息-sourceLang:" + sourceLang + " targetLang:" + targetLang + " text:" + text);
        JSONObject resTrans = new JSONObject();

        try {
            String projectId = "ghb-translate";
            String targetLanguage = "en";

            // 语言识别
            if (KHUtil.isNull(sourceLang)) {
                targetLanguage = "zh-CN";
            } else {
                targetLanguage = targetLang;
            }

            resTrans = translateText(projectId, targetLanguage, text);
            log.debug("调用Google翻译V3返回信息-output:" + resTrans);

        } catch (Exception e) {
            log.error("调用Google翻译V3接口处理异常", e);
            resTrans.put("code", -1);
            resTrans.put("message", "调用Google翻译V3调用异常:" + e.getMessage());
        }

        log.debug("调用Google翻译V3返回信息-最终结果:" + resTrans);
        return resTrans;
    }

    public static JSONObject translateText(String projectId, String targetLanguage, String text) throws IOException {
        JSONObject transJson = JSONObject.fromObject("{\"data\":{\"translations\":[{\"translatedText\":\"\"}]},\"code\":0,\"message\":\"调用成功\"}");
        StringBuffer transText = new StringBuffer();
        log.debug("translateText Google翻译V3 -projectId:" + projectId + " targetLanguage:" + targetLanguage + " text:" + text);
        try {
            TranslationServiceClient client = TranslationServiceClient.create()

            LocationName parent = LocationName.of(projectId, "global");
            TranslateTextRequest request = TranslateTextRequest.newBuilder().setParent(parent.toString()).setMimeType("text/plain").setTargetLanguageCode(targetLanguage).addContents(text).build();

            TranslateTextResponse response = client.translateText(request);

            for (Translation translation : response.getTranslationsList()) {
                transText.append(translation.getTranslatedText());
            }
            log.debug("translateText Google翻译V3 结果:" + transText);
            transJson.getJSONObject("data").getJSONArray("translations").getJSONObject(0).put("translatedText", transText.toString());
        } catch (Exception e) {
            log.error("translateText Google翻译V3 处理异常", e);
            transJson.put("code", -1);
            transJson.put("message", e.getMessage());
            transJson.getJSONObject("data").getJSONArray("translations").getJSONObject(0).put("translatedText", text);
        }
        log.debug("translateText Google翻译V3 JSON结果:" + transJson.toString());
        return transJson;
    }

    /**
     * @param params : 入参信息Map
     * @return String
     * @author LiJT
     * @description TODO
     * @date 2023-09-27 15:27
     */
    public static String getMapToForm(Map<String, String> params) {
        if (params == null) {
            return "";
        }

        StringBuilder builder = new StringBuilder();

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { // 过滤空的key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;
        }

        return builder.toString();
    }

    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     *
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原文
     */
    public static String encode(String input) {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return input;
    }
}